import LocalStorageConstant from "../constant/LocalStorageConstant";
import DictApi from "../api/DictApi";
import {UniStorage} from "@/util/uniUtils";

export class DictUtil{
    /**
     * 获取字典数组
     * @param dictCode 字典Code
     * @return List<Map>
     */
    static async initDictOptions(dictCode) {
        if (!dictCode) {
            return '字典Code不能为空!';
        }
        //优先从缓存中读取字典配置
        if(getDictItemsFromCache(dictCode)){
            let res = {}
            console.log("从缓存中读取")
            res.result = getDictItemsFromCache(dictCode);
            res.success = true;
            return res;
        }
        console.log("从后台查询")
        //获取字典数组
        return await DictApi.getDictItemsByCode(dictCode);
    }
    /**
     * 翻译字段值对应的文本
     * @param dictCode
     * @param key
     * @returns {*|string}
     */
     static filterDictTextByCache(dictCode, key) {
        if (key == null || key.length === 0) {
            return;
        }
        if (!dictCode) {
            return '字典Code不能为空!';
        }
        //优先从缓存中读取字典配置
        if (getDictItemsFromCache(dictCode)) {
            let item = getDictItemsFromCache(dictCode).filter(t => t["value"] == key)
            if (item && item.length > 0) {
                return item[0]["text"]
            }
        }
    }
    //从缓存中获取字典配置
    static getDictItemsFromCache(dictCode) {
        let dictList = UniStorage.get(LocalStorageConstant.DICT_LIST);
        if (dictList && dictList[dictCode]) {
            return dictList[dictCode];
        }
    }
    /**
     * 翻译分类字典
     *
     * @param key 根节点code
     * @param code 待翻译节点code
     * @returns {string}
     */
    static filterCategoryDictTextByCache(key, code) {
        if (!key || !code) {
            return '';
        }
        // 从缓存中获取数据
        let dictList = getCategoryDictFromCache(key)
        if (dictList) {
            let find = dictList.find(item => item.code === code)
            if (find) {
                let container = []
                findTree(dictList, find.id, container)
                return container.reverse().map(item => item.name).join('/')
            } else {
                return ''
            }
        }
        return ''
    }
}




/**
 * 向上查找树结构
 * @param array 待查找集合
 * @param id 当前元素id
 * @param container 找到后放置的容器
 */
function findTree(array, id, container) {
    let find = array.find(item => item.id === id)
    if (find) {
        container.push(find)
        let {parentId} = find
        if (parentId) {
            findTree(array, parentId, container)
        }
    }
}

//从缓存中获取分类字典
function getCategoryDictFromCache(dictCode) {
    let categoryDict = UniStorage.get(LocalStorageConstant.CATEGORY_LIST);
    if (categoryDict && categoryDict[dictCode]) {
        return categoryDict [dictCode];
    }
}

